package LeetCode.leetcode21MergeSqList;

public class MergeList {
    public static void main(String[] args) {


    }

    /**
     * 合并两个有序链表
     *
     * @param l1
     * @param l2
     * @return
     */
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        //新链表的头结点
        ListNode headNew = new ListNode();
        //指向l1的指针和指向l2的指针
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        //指向新链表的尾结点(临时)
        ListNode tail = null;
        tail = headNew;
        while (cur1 != null && cur2 != null) {
            //如果cur2更小，将cur2加入新链表
            if (cur1.val >= cur2.val) {
                //将cur2加入新链表
                tail.next = cur2;
                //后移cur2
                cur2 = cur2.next;
                //后移tail
                tail = tail.next;
            } else {
                tail.next = cur1;
                cur1 = cur1.next;
                tail = tail.next;
            }
        }
        if (cur1 == null) {
            tail.next = cur2;
        } else {
            tail.next = cur1;
        }
        return headNew.next;

    }
}
